import numpy as np
import cv2


def sliding_window(image, window_size, step_size_ratio):
    """
    使用滑动窗口切分图片并保存切分后的子图
    """
    # 计算步长
    step_size = (int(window_size[0] * step_size_ratio), int(window_size[1] * step_size_ratio))
    
    # 获取图像尺寸
    img_height, img_width = image.shape[:2]
    win_width, win_height = window_size
    
    # 遍历图像进行切分
    windows = []
    for y in range(0, img_height - win_height + 1, step_size[1]):
        for x in range(0, img_width - win_width + 1, step_size[0]):
            # 提取窗口区域
            window = image[y:y + win_height, x:x + win_width]
            windows.append(np.expand_dims(window, axis=0))
    
    windows = np.vstack(windows)
    num_w = int((img_width - win_width + 1) / step_size[0]) + 1
    num_h = int((img_height - win_height + 1) / step_size[1]) + 1
    return windows, num_w, num_h


path = '/data/dog_8k.png'
mat = cv2.imread(path)
window_size = (640, 640)  # 窗口宽度和高度
step_size_ratio = 0.6    # x方向和y方向的步长
res, num_w, num_h = sliding_window(mat, window_size, step_size_ratio)

# save
import os
save_dir = "/culn/crop_py"
if not os.path.exists(save_dir):
    os.makedirs(save_dir)
for i in range(num_h):
    for j in range(num_w):
        idx = i * num_w + j
        crop_img = res[idx]
        save_path = os.path.join(save_dir, str(i) + '_' + str(j) + '.png')
        cv2.imwrite(save_path, crop_img)

print('finish')
